﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Globalization;
using System.Resources;
using System.Collections.Specialized;
using PlugNT.Pack.Imager;

namespace PlugNT.Pack.Upload
{
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultProperty("RootPath")]
    [DefaultEvent("UploadChanged")]
    [ToolboxData("<{0}:UploadImage runat=server></{0}:UploadImage>")]
    public class UploadImage : Panel, INamingContainer
    {

        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string RootPath
        {
            get
            {
                String s = (String)ViewState["AguiRootPath"];
                return ((s == null) ? String.Empty : ((s.EndsWith("/")) ? s : s + "/"));
            }

            set
            {
                ViewState["AguiRootPath"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(""), Localizable(true)]
        public string UploadPath
        {
            get
            {
                String s = (String)ViewState["AguiUploadPath"];
                return ((s == null) ? String.Empty : ((s.EndsWith("/")) ? s.TrimEnd('/') : s));
            }

            set
            {
                ViewState["AguiUploadPath"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue("")]
        public string WaterPath
        {
            get
            {
                String s = (String)ViewState["AguiWaterPath"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["AguiWaterPath"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue("")]
        public string WaterText
        {
            get
            {
                String s = (String)ViewState["AguiWaterText"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["AguiWaterText"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue("9")]
        public string WaterPostion
        {
            get
            {
                String s = (String)ViewState["AguiWaterPostion"];
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["AguiWaterPostion"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue(".gif|.jpg|.jpeg|.png")]
        public string AllowExtNames
        {
            get
            {
                String s = (String)ViewState["AguiAllowExtNames"];
                return ((s == null) ? String.Empty : "|" + s.Trim().ToLower() + "|");
            }
            set
            {
                ViewState["AguiAllowExtNames"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue("")]
        public string IsFullScreen
        {
            get
            {
                String s = (String)ViewState["AguiIsFullScreen"];
                return ((s == null) ? String.Empty : s.Trim().ToLower());
            }
            set
            {
                ViewState["AguiIsFullScreen"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue("")]
        public string ScreenHeight
        {
            get
            {
                String s = (String)ViewState["AguiScreenHeight"];
                return ((s == null) ? String.Empty : s.Trim());
            }
            set
            {
                ViewState["AguiScreenHeight"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue("false")]
        public string IsWaterImage
        {
            get
            {
                String s = (String)ViewState["AguiIsWaterImage"];
                return ((s == null) ? String.Empty : s.Trim().ToLower());
            }

            set
            {
                ViewState["AguiIsWaterImage"] = value;
            }
        }

        [Bindable(true), Category("Appearance"), DefaultValue("false")]
        public string ClientObjectString
        {
            get
            {
                String s = ((String)ViewState["ClientObjectString"]).Trim();
                if (s != "" || ClientObjectType != "")
                {
                    s = "'" + s + "','" + ClientObjectType + "'";
                }
                return ((s == null) ? String.Empty : s);
            }

            set
            {
                ViewState["ClientObjectString"] = value;
            }
        }

        /// <summary>
        /// text,object,function，func-obj
        /// </summary>
        [Bindable(false), Category("Behavior"), DefaultValue("text"), TypeConverter(typeof(ClientObjectTypeControlsConverter)), Description("要滚动的对象。")]
        public string ClientObjectType
        {
            get
            {
                String s = (String)ViewState["ClientObjectType"];
                return ((s == null) ? String.Empty : s.Trim());
            }
            set
            {
                ViewState["ClientObjectType"] = value;
            }
        }



        private string _watertext = "";
        private string _currentpath = "";
        private string _aguiimagegallery = "";
        private string strStatus = "";
        private bool flgStatus = true;

        private static readonly object EventUploadChanged = new object();



        #region 初始化文件列表的控件InitFileInfoList

        private string InitFileInfoList(string path)
        {
            _currentpath = path;   //初始化时就赋值当前路径
            StringBuilder sb = new StringBuilder();

            string newpath = HttpContext.Current.Server.MapPath("/");        //根目录
            newpath = newpath + path;

            string[] files = Directory.GetFiles(newpath);
            string[] directories = Directory.GetDirectories(newpath);

            //向上链接
            if (path.Length > UploadPath.Trim().Length)
            {
                string backpath = path.Substring(0, path.LastIndexOf('/'));
                sb.Append("<div class=\"thumbnail\">");
                sb.Append("<div class=\"imageholder\" unselectable=\"on\" onclick=\"Agui_FolderClick(this);\" ondblclick=\"Agui_GoToFolder('AguiImageGallery','" + RootPath.Trim() + "','" + backpath + "');\">");
                sb.Append("<img src=\"" + RootPath.Trim() + "images/folder.up.gif\" title=\"向上\" unselectable=\"on\" align=\"absmiddle\" vspace=\"26\" />");
                sb.Append("</div>");
                sb.Append("<div class=\"titleHolder\">向上</div>");
                sb.Append("</div>");
            }
            //文件夹
            for (int i = 0; i < directories.Length; i++)
            {
                FileInfo file = new FileInfo(directories[i]);
                if (file.Name != "Thumbs.db")
                {
                    sb.Append("<div class=\"thumbnail\">");
                    sb.Append("<div class=\"imageholder\" unselectable=\"on\" onclick=\"Agui_FolderClick(this,'" + file.Name + "');\" ondblclick=\"Agui_GoToFolder('AguiImageGallery','" + path + "','" + path + "/" + file.Name + "');\">");
                    sb.Append("<img src=\"" + RootPath.Trim() + "images/folder.big.gif\" title=\"" + path + "/" + file.Name + "\" unselectable=\"on\" align=\"absmiddle\" vspace=\"19\" />");
                    sb.Append("</div>");
                    sb.Append("<div class=\"titleHolder\">" + file.Name + "</div>");
                    sb.Append("</div>");
                }
            }
            //图片文件
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo file = new FileInfo(files[i]);
                if (file.Name != "Thumbs.db")
                {
                    int iflg = file.Name.LastIndexOf(".");               //取得文件名中最后一个"."的索引
                    string newext = file.Name.Substring(iflg).ToLower();           //获取文件扩展名
                    if (AllowExtNames.Contains("|" + newext + "|"))
                    {
                        //System.Drawing.Image objImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(path + "/" + file.Name));
                        sb.Append("<div class=\"thumbnail\">");
                        if (IsFullScreen == "true")
                        {
                            sb.Append("<div class=\"imageholder\" unselectable=\"on\" onclick=\"Agui_PreviewImage(this,'" + path + "','" + file.Name + "','" + file.Length + " KB');\">");
                        }
                        else
                        {
                            sb.Append("<div class=\"imageholder\" unselectable=\"on\" onclick=\"Agui_PreviewImage(this,'" + path + "','" + file.Name + "','" + file.Length + " KB');\" ondblclick=\"Agui_InsertImage(" + ClientObjectString + ");\">");
                        }
                        sb.Append("<img src=\"" + path + "/" + file.Name + "\" title=\"" + path + "" + file.Name + "\" unselectable=\"on\" align=\"absmiddle\" width=\"100\" height=\"71\" vspace=\"5\" />");
                        sb.Append("</div>");
                        sb.Append("<div class=\"titleHolder\">" + file.Name + "</div>");
                        sb.Append("</div>");
                        //objImage.Dispose();
                    }
                }
            }
            return sb.ToString();
        }
        #endregion

        #region 提交数据
        private void PostData()
        {
            string target = HttpContext.Current.Request.Params["__EVENTTARGET"];
            string args = HttpContext.Current.Request.Params["__EVENTARGUMENT"];

            System.Web.UI.Control control = null;
            bool findControl = false;
            foreach (string controllName in HttpContext.Current.Request.Form)
            {
                control = this.FindControl(controllName);
                if (control is IPostBackEventHandler)
                {
                    findControl = true;
                    break;
                }
            }
            if (!findControl && HttpContext.Current.Request.Form["__EVENTTARGET"] != null)
            {
                //control = this.FindControl(HttpContext.Current.Request.Form["__EVENTTARGET"].Replace(this.UniqueID + ":", ""));
                if (HttpContext.Current.Request.Form["__EVENTTARGET"].Replace(this.UniqueID + ":", "") == "AguiImageGallery")
                {
                    string gopath = _currentpath;
                    if (args.StartsWith("CreateFolder:"))
                    {
                        string para = "CreateFolder:";
                        CreatFolder(args.Substring(para.Length), _currentpath);     //args.TrimStart(para.ToCharArray()) 不能用这个很容易出现错误！
                    }
                    else if (args.StartsWith("DeleteFolder:"))
                    {
                        string para = "DeleteFolder:";
                        DeleteFolder(args.Substring(para.Length), _currentpath);
                    }
                    else if (args.StartsWith("DeleteImage:"))
                    {
                        string para = "DeleteImage:";
                        DeleteImg(args.Substring(para.Length), _currentpath);
                    }
                    else if (args.StartsWith("GoToFolder:"))
                    {
                        string para = "GoToFolder:";
                        gopath = args.Substring(para.Length);
                    }
                    else if (args.StartsWith("UploadImage"))
                    {
                        string para = "UploadImage:";    //如果参数是UploadImage则后面参数是“是”或“否”而不是路径
                        UploadImages(false, args.Substring(para.Length - 1), _currentpath);
                    }
                    else if (args.StartsWith("UploadAllImage"))
                    {
                        string para = "UploadAllImage:";  //如果参数是UploadAllImage则后面参数是“是”或“否”而不是路径
                        UploadImages(true, args.Substring(para.Length - 1), _currentpath);
                    }
                    //((System.Web.UI.HtmlControls.HtmlGenericControl)control).InnerHtml = InitFileInfoList(gopath);
                    _aguiimagegallery = InitFileInfoList(gopath);
                }
            }
            else
            {
                _aguiimagegallery = "初始化错误！";
            }
        }
        #endregion

        #region 新建文件夹
        private void CreatFolder(string name, string path)
        {
            string newpath = HttpContext.Current.Server.MapPath("/");        //根目录
            newpath = newpath + path.Replace("/", @"\");
            string[] directories = Directory.GetDirectories(newpath);
            newpath = newpath + "\\" + name;
            bool flg = false;

            for (int i = 0; i < directories.Length; i++)
            {
                FileInfo file = new FileInfo(directories[i]);
                if (file.Name.ToString() == name)
                {
                    flg = true;
                    break;
                }
            }

            if (!flg)
            {
                DirectoryInfo dir = new DirectoryInfo(newpath);
                dir.Create();
                //Directory.CreateDirectory(newpath);
            }
        }
        #endregion

        #region 删除文件夹
        private void DeleteFolder(string name, string path)
        {
            string newpath = HttpContext.Current.Server.MapPath("/");        //根目录
            newpath = newpath + path.Replace("/", @"\");
            string[] directories = Directory.GetDirectories(newpath);
            newpath = newpath + @"\" + name;
            for (int i = 0; i < directories.Length; i++)
            {
                FileInfo file = new FileInfo(directories[i]);
                if (file.Name != "Thumbs.db" && name == file.Name)
                {
                    if (Directory.Exists(newpath))
                    {
                        //Directory.Delete(newpath, true);
                        DirectoryInfo dir = new DirectoryInfo(newpath);
                        dir.Delete(true);
                        break;
                    }
                }
            }
        }
        #endregion

        #region 删除图片文件
        private void DeleteImg(string name, string path)
        {
            string newpath = HttpContext.Current.Server.MapPath("/");        //根目录
            newpath = newpath + path.Replace("/", @"\");
            string[] files = Directory.GetFiles(newpath);

            for (int i = 0; i < files.Length; i++)
            {
                FileInfo file = new FileInfo(files[i]);
                if (file.Name != "Thumbs.db" && name == file.Name)
                {
                    file.Delete();
                    break;
                }
            }
        }
        #endregion

        #region 上传图片
        private void UploadImages(bool isall, string iswater, string path)
        {
            if (path.Length <= UploadPath.Trim().Length)
            {
                strStatus = "上传图片状态<hr color=\"red\" />根目录不允许上传图片!";
                flgStatus = false;
                return;
            }
            if (isall)   //批量上传图片
            {
                SaveImages(iswater, path);
            }
            else        //上传单个图片
            {
                string newpath = HttpContext.Current.Server.MapPath("/");              //根目录
                newpath = newpath + path.Replace("/", @"\");

                HttpFileCollection files = HttpContext.Current.Request.Files;
                HttpPostedFile postedFile = files["command_UploadFile"];

                string photoName1 = postedFile.FileName;    //获取初始文件名
                int i = photoName1.LastIndexOf(".");                           //取得文件名中最后一个"."的索引
                string newext = photoName1.Substring(i).ToLower();                       //获取文件扩展名
                string _filename = System.IO.Path.GetFileName(photoName1);
                string longname = newpath + @"\" + _filename;
                if (AllowExtNames.Contains("|" + newext + "|"))
                {
                    if (File.Exists(longname))
                    {
                        strStatus = "上传图片状态<hr color=\"red\" />文件  " + _filename + "　已存在！";
                        flgStatus = false;
                    }
                    else
                    {
                        string uploadErr = "";
                        if (iswater.Trim() == "true")
                        {
                            if (_watertext == "")
                            {
                                uploadErr = CreateWaterImage(newpath, _filename, postedFile.InputStream);
                            }
                            else
                            {
                                uploadErr = CreateWaterText(newpath, _filename, postedFile.InputStream);
                            }
                        }
                        else
                        {
                            newpath = newpath + @"\" + _filename;
                            postedFile.SaveAs(newpath);
                        }
                        if (uploadErr != "")
                        {
                            strStatus = "文件  " + _filename + "　上传失败！" + uploadErr + "<br><hr>";
                            flgStatus = false;
                        }
                        else
                        {
                            System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
                            strMsg.Append("上传状态<hr color=\"red\" />");
                            strMsg.Append("文件类型：" + postedFile.ContentType.ToString() + "<br>");
                            strMsg.Append("文件全路径：" + postedFile.FileName + "<br>");
                            strMsg.Append("文件名：" + _filename + "<br>");
                            strMsg.Append(_filename + "　上传成功！<br><hr>");
                            strStatus = strMsg.ToString();
                        }
                    }
                    InitFileInfoList(path);
                }
                else
                {
                    strStatus = "上传图片状态<hr color=\"red\" />文件  " + _filename + "  格式不正确!";
                    flgStatus = false;
                    InitFileInfoList(path);
                }
            }
            OnUploadChanged(new EventArgs());
        }
        #endregion

        #region 批量保存上传的图片
        private bool SaveImages(string iswater, string path)
        {

            HttpFileCollection files = HttpContext.Current.Request.Files;
            //========状态信息==============================================
            System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
            //================保存的路径==================================
            string longname = "";
            strMsg.Append("上传状态<hr color=\"red\" />");
            try
            {
                //======遍历File表单元素=========================================
                for (int iFile = 0; iFile < files.Count; iFile++)
                {
                    //=======检查文件扩展名字=============================
                    HttpPostedFile postedFile = files[iFile];
                    string fileName, fileExtension;
                    fileName = System.IO.Path.GetFileName(postedFile.FileName);
                    //====================================================
                    if (fileName != "")
                    {

                        //=========文件已存在==================================
                        string newpath = HttpContext.Current.Server.MapPath("/");        //根目录
                        newpath = newpath + path.Replace("/", @"\");
                        newpath = newpath + @"\";
                        longname = newpath + fileName;
                        if (File.Exists(longname))
                        {
                            strMsg.Append("文件　" + fileName + "　已存在！<br><hr>");
                            flgStatus = false;
                            continue;
                        }
                        int iflg = fileName.LastIndexOf(".");               //取得文件名中最后一个"."的索引
                        string newext = fileName.Substring(iflg).ToLower();           //获取文件扩展名

                        if (!AllowExtNames.Contains("|" + newext + "|"))
                        {
                            strMsg.Append("文件　" + fileName + "　格式不正确！<br><hr>");
                            flgStatus = false;
                            continue;
                        }
                        //========状态信息=================================================
                        fileExtension = System.IO.Path.GetExtension(fileName);
                        string uploadErr = "";
                        //=================注意：可能要修改你的文件夹的匿名写入权限。=============================
                        if (iswater.Trim() == "true")
                        {
                            if (_watertext == "")
                            {
                                uploadErr = CreateWaterImage(newpath, fileName, postedFile.InputStream);
                            }
                            else
                            {
                                uploadErr = CreateWaterText(newpath, fileName, postedFile.InputStream);
                            }
                        }
                        else
                        {
                            postedFile.SaveAs(longname);
                        }
                        if (uploadErr != "")
                        {
                            strMsg.Append("文件　" + fileName + "　上传失败！" + uploadErr + "<br><hr>");
                            flgStatus = false;
                        }
                        else
                        {
                            strMsg.Append("文件类型：" + postedFile.ContentType.ToString() + "<br>");
                            strMsg.Append("文件全路径：" + postedFile.FileName + "<br>");
                            strMsg.Append("文件名：" + fileName + "<br>");
                            strMsg.Append(fileName + "　上传成功！<br><hr>");
                        }
                    }
                }
                strStatus = strMsg.ToString();
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 生成水印图片
        private string CreateWaterImage(string path, string filename, Stream inputstream)
        {
            WaterMark wm = new WaterMark();
            wm.WaterImagePath = WaterPath;
            wm.SavePath = path + @"\" + filename;
            wm.ImgStream = inputstream;
            wm.Waterstatus = int.Parse(WaterPostion.Trim());
            wm.Transparency = 8;
            wm.Quality = 80;
            return wm.SaveImageWater();
        }
        #endregion

        #region 生成水印文字
        private string CreateWaterText(string path, string filename, Stream inputstream)
        {
            WaterMark wm = new WaterMark();
            wm.SavePath = path + @"\" + filename;
            wm.ImgStream = inputstream;
            wm.Waterstatus = int.Parse(WaterPostion.Trim());
            wm.WaterFontName = "宋体";
            wm.WaterFontSize = 12;
            wm.WaterText = _watertext;
            wm.Quality = 80;
            return wm.SaveStringWater();
        }
        #endregion


        #region 根据日期时间得到上传图片名称（废弃）
        private string GetImgName(string oldName, int img_count)
        {
            StringBuilder newname = new StringBuilder();
            newname.Append(System.DateTime.Now.Year.ToString());
            newname.Append(System.DateTime.Now.Month.ToString());
            newname.Append(System.DateTime.Now.Day.ToString());
            newname.Append(System.DateTime.Now.Hour.ToString());
            newname.Append(System.DateTime.Now.Minute.ToString());
            newname.Append(System.DateTime.Now.Second.ToString());
            newname.Append(System.DateTime.Now.Millisecond.ToString() + img_count.ToString());

            string extname = oldName.Substring(oldName.LastIndexOf('.'));
            string fullname = newname.ToString() + extname;
            return fullname;
        }
        #endregion

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //code
        }
        protected override void OnLoad(EventArgs e)
        {
            EventArgs args = new EventArgs();
            base.OnLoad(e);
        }
        protected override void OnPreRender(EventArgs e)
        {
            //code script
            base.OnPreRender(e);
        }

        public event EventHandler UploadChanged
        {
            add
            {
                base.Events.AddHandler(UploadImage.EventUploadChanged, value);
            }
            remove
            {
                base.Events.RemoveHandler(UploadImage.EventUploadChanged, value);
            }
        }

        protected virtual void OnUploadChanged(EventArgs e)
        {
            EventHandler handler = (EventHandler)base.Events[UploadImage.EventUploadChanged];
            if (handler != null)
                handler(this, e);
        }


        protected override void RenderContents(HtmlTextWriter output)
        {
            string errStr = "";
            if (RootPath.Trim() == "")
            {
                errStr += "<br><pre>      组件（UploadImage.css，UploadImage.js，及images下的图片）根目录未设置！</pre>";
            }
            if (UploadPath.Trim() == "")
            {
                errStr += "<br><pre>      图片上传路径未设置！</pre>";
            }
            if (WaterPath.Trim() == "")
            {
                errStr += "<br><pre>      水印图片路径未设置（如果启用水印文字可设置水印文字）！</pre>";
            }
            if (errStr != "")
            {
                output.Write(errStr);
                return;
            }

            _currentpath = (HttpContext.Current.Request.Form["__CURRENTPATH"] == null) ? "" : HttpContext.Current.Request.Form["__CURRENTPATH"].Trim();
            _watertext = WaterText.Trim();
            if (_currentpath != "")
            {
                PostData();
            }
            else
            {
                _aguiimagegallery = InitFileInfoList(UploadPath.Trim());
            }

            string html = @"
            <link href='$RootPath$UploadImage.css' rel='stylesheet' type='text/css' />
            <style type='text/css'>
            #TdGallerySideBar{ $IsFullScreen$}
            </style>
            <script type='text/javascript' src='$RootPath$UploadImage.js'></script> 
            <form id='AguiForm1' name='AguiForm1' method='post' enctype='multipart/form-data'>
            <input type='hidden' name='__EVENTTARGET' id='__EVENTTARGET' value='' />
            <input type='hidden' name='__EVENTARGUMENT' id='__EVENTARGUMENT' value='' />
            <input type='hidden' name='__CURRENTPATH' id='__CURRENTPATH' value='$CurrentPath$'  />
            <input type='hidden' name='toolsimgpath' id='toolsimgpath' value='$RootPath$'  />
            <script type='text/javascript'>
            //<![CDATA[
            var theForm = document.forms['AguiForm1'];
            if (!theForm) {
                theForm = document.AguiForm1;
            }
            function __doPostBack(eventTarget, eventArgument) {
                if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
                    theForm.__EVENTTARGET.value = eventTarget;
                    theForm.__EVENTARGUMENT.value = eventArgument;
                    theForm.submit();
                }
            }
            //]]>
            </script>
            <table width='100%' height='100%' cellpadding='0' cellspacing='0' border='0'>
                <tr>
                    <td style='width:100%; float:left;' valign='top' align='left'>
	                    <div id='AguiImageGallery' class='frm_show'>
                         $AguiImageGallery$
                        </div>
                        <div id='loadfilesdiv' class='frm_hid'>
                            <input id='img_table_cols' type='hidden' value='4'>
                            <div>
                                <table border=0 cellpadding=0 cellspacing=0 width=100%>
                                    <tr id=uploadTr runat=server>
                                        <td>
                                            <TABLE id='uploadTab' style='HEIGHT: 46px' cellSpacing='1' cellPadding='1' width='100%' border='0'>
	                                            <TR class='tab_tr'>           
		                                            <TD style='WIDTH: 250px'>
			                                            <TABLE>
				                                            <TR class='tab_tr'>
					                                            <TD><SPAN style='CURSOR: hand' onclick='ReSetFile()'><IMG src='$RootPath$images/new.ico' border='0'></SPAN></TD>
					                                            <TD><SPAN style='CURSOR: hand' onclick='RefreshFile()'><IMG src='$RootPath$images/refresh.ico' border='0'></SPAN></TD>
					                                            <TD><SPAN style='CURSOR: hand' onclick='AddFile();'><IMG src='$RootPath$images/add.ico' border='0'></SPAN></TD>
				                                            </TR>
			                                            </TABLE>
		                                            </TD>
		                                            <TD style='display:none;'>
		                                                <a href='#' title='上传'><img onclick='UploadImages();' style=' border:0px;' src='$RootPath$images/upload.gif' /></a>
			                                        </TD>
	                                            </TR>
	                                            <TR class='tab_tr'>
		                                            <TD colSpan='2'>
			                                            <DIV id='filesdiv' style=' display:block;'></DIV>
			                                            <DIV id='uploadState' style='display: none;' align='center'>
				                                            <TABLE cellSpacing='0' cellPadding='0' border='0' style=' width:100%; height:350px;'>
					                                            <TR>
						                                            <TD align='center' valign='middle'><IMG  style=' border:0px;' src='$RootPath$images/uploading.gif'><br /><br />正在上传文件请稍后...</TD>
					                                            </TR>
				                                            </TABLE>
			                                            </DIV>
		                                            </TD>
	                                            </TR>
                                            </TABLE>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                        <div id='statusdiv' class='frm_hid'>
                            <div id='strStatus' style=' width:100%' >
                                $strStatus$
                            </div>          
                        </div>
                        <div style='list-style:none; float:left;'>
                            <table border='0' cellpadding='0' cellspacing='0'>
                                <tr>
                                    <td style=' width:103px; height:17px;' id='span1' class='unselect_span' onclick='SwapDiv(1);'>&nbsp;批量上传文件&nbsp;</td>
                                    <td style=' width:103px; height:17px;' id='span2' class='select_span' onclick='SwapDiv(2);'>文件列表&nbsp;</td>                
                                    <td style=' width:103px; height:17px;' id='span3' class='unselect_span' onclick='SwapDiv(3);'>&nbsp;文件操作状态&nbsp;</td>
                                </tr>
                            </table>
                        </div>
                        <div style='clear:both;'>
			                <table>
			                <tr><td colspan='2'><div>图片效果</div></td>
				                <td>
				                    <input id='IsWaterImage' type='checkbox'$IsWaterImage$ /><span style=' cursor:hand;' onclick='SetWater();' >是否添加水印</span>
				                </td>			
				                <td></td>
			                </tr>			
			                <tr><td colspan='2'><div id='img_feedback_title'>选择状态</div></td>
				                <td><input type='text' id='img_feedback_message' disabled='disabled' style='width:300px;' /></td>			
				                <td>	
					                <input type='button' id='command_DeleteFolderButton' class='button' value='删除文件夹' onclick=$'$if(confirm('删除文件夹会导致应用程序重起而使Session过期，确定删除此目录吗！')){Agui_DeleteFolder('AguiImageGallery');}$'$ style='display:none;' />
					                <input type='button' id='command_DeleteImageButton' class='button' value='删除图片' onclick=$'$Agui_DeleteImage('AguiImageGallery');$'$ style='display:none;' />
				                </td>
			                </tr>

			                <tr><td>文件</td>
			                <td><img src='$RootPath$images/image.gif' width='16' height='16' /></td>
			                <td>			
                                <input name='command_UploadFile' type='file' id='command_UploadFile' class='button' size='42' style='width: 300px;' />
			                </td><td>
				                <input type='button' id='command_UploadButton' class='button' value='上传' onclick='UploadImages();' />
			                </td><td>
				                &nbsp;
			                </td>
			                </tr>
			                <tr><td>文件夹名</td>
			                <td><img src='$RootPath$images/folder.small.gif' width='16' height='16' /></td>
			                <td>
				                <input type='text' id='command_NewFolderName' style='width:300px;' />
			                </td><td>
				                <input type='button' id='command_NewFolderButton' class='button' value='创建文件夹' onclick=$'$Agui_CreateFolder('AguiImageGallery');$'$ />
			                </td><td>
				                &nbsp;				
			                </td>
			                </tr>
			                </table>
                        </div>
                    </td>
                    <td id='TdGallerySideBar' width='235' valign='top' style='padding:5px;'>
	                    <div id='GallerySideBar'>
	                    <fieldset style='width:220px;'><legend>当前图片视图</legend>
		                    <div style='width:212px; height:150px; overflow:auto;'>
			                    <img id='img_preview' src='$RootPath$images/spacer.gif' />				
		                    </div>
	                    </fieldset>
                        <br/>
                        <fieldset style='width:220px;'><legend>是否网络图片</legend>
                            <table>
                                <tr>
                                    <td><input id='img_web_cbx' type='checkbox' onclick='Agui_PreviewImageSrc();' /></td>
                                    <td><input id='img_web_url' type='text' style='width:180px;' disabled='true' onPropertyChange='Agui_PreviewImageSrc();' value='http://' /></td>
                                </tr>
                            </table>
                        </fieldset>
                        <br/>
	                    <fieldset style='width:220px;$ClientObjectType$'><legend>当前图片属性</legend>
		                    <table>
			                    <tr>
				                    <td valign='top'><input type='radio' id='img_dim_original' name='img_dim' onclick='Agui_DimensionChange(this);' checked='true' /><label for='img_dim_original'>原始大小</a></td>
				                    <td><input type='text' id='img_width' style='width:45px;' onchange='Agui_UpdatePreview(this);' disabled='true' />x<input type='text' id='img_height' style='width:45px;' onchange='Agui_UpdatePreview(this);' disabled='true' />
				                    </td>
			                    </tr>
			                    <tr>
				                    <td valign='top'><input type='radio' id='img_dim_custom' name='img_dim' onclick='Agui_DimensionChange(this);' /><label for='img_dim_custom'>重置大小</a></td>
				                    <td><input type='text' id='img_width_custom' style='width:45px;' onkeyup='Agui_UpdatePreview(this);' disabled='true' />x<input type='text' id='img_height_custom' style='width:45px;' onkeyup='Agui_UpdatePreview(this);' disabled='true' />
					                    <br />
					                    <input type='checkbox' id='img_lockRatio' checked='checked'  /> <label for='img_lockRatio'>锁定比例</label>
				                    </td>
			                    </tr>
			                    <tr>
				                    <td><input type='radio' id='img_dim_percentage' name='img_dim' onclick='Agui_DimensionChange(this);' /><label for='img_dim_percentage'>百分比</label></td>
				                    <td><input type='text' id='img_percentage' style='width:45px;' onkeyup='Agui_UpdatePreview(this);' disabled='true' />									
				                    </td>
			                    </tr>
		                    </table>
		                    <table>
			                    <tr>
			                    <tr><td class='f_title'>对齐方式</td>
				                    <td><select id='img_align' >
						                    <option value=''>无设置</option>
						                    <option value='top'>上边</option>
						                    <option value='bottom'>下边</option>
						                    <option value='left'>左边</option>
						                    <option value='right'>右边</option>
						                    <option value='center'>中间</option>
						                    <option value='absmiddle'>正中心</option>
					                    </select>
					                    边框<input type='text' id='img_border' style='width:30px;' />					
					                    </td>
				                    </tr>	
			                    <tr><td class='f_title'>垂直边距</td>
				                    <td><input type='text' id='img_vspace' style='width:30px;'/>&nbsp;&nbsp;水平边距<input type='text' id='img_hspace' style='width:30px;'/></td>
				                    </tr>
			                    <tr>
			                    <tr><td class='f_title'>Alt属性</td>
				                    <td><input type='text' id='img_alt' style='width:150px;'/></td>
				                    </tr>
			                    <tr style='display:none;'><td class='f_title'>标题</td>
				                    <td><input type='text' id='img_title' style='width:150px;'/></td>
				                </tr>																						
		                    </table>
	                    </fieldset>
	                    <div style='text-align:center;'>
		                    <input type='button' class='button' value='插入' onclick=$'$Agui_InsertImage($ClientObjectString$);$'$ />         <!-- Agui_InsertImage(); //-->
	                    </div>
	                    </div>
                     </td>
                     <td width='1'><div style='display:block; height:$ScreenHeight$; width:1px;'></div></td>
                </tr>
            </table>
            <script language='javascript' type='text/javascript'>
            $funStatus$
            </script>
            </form>
            ";
            html = html.Replace("$'$", "\"");
            html = html.Replace("$RootPath$", RootPath.Trim());
            html = html.Replace("$AguiImageGallery$", _aguiimagegallery);
            html = html.Replace("$CurrentPath$", _currentpath);
            html = (IsFullScreen == "true") ? html.Replace("$IsFullScreen$", "display:none;") : html.Replace("$IsFullScreen$", "");
            html = (IsWaterImage == "true") ? html.Replace("$IsWaterImage$", " checked='checked'") : html.Replace("$IsWaterImage$", "");
            html = (ScreenHeight == "") ? html.Replace("$ScreenHeight$", "300px") : html.Replace("$ScreenHeight$", ScreenHeight);
            html = (ClientObjectType == "text" || ClientObjectType == "function") ? html.Replace("$ClientObjectType$", "display:none;") : html.Replace("$ClientObjectType$", "");
            html = html.Replace("$ClientObjectString$", ClientObjectString);
            if (strStatus != "")
            {
                html = html.Replace("$strStatus$", strStatus);
                html = (!flgStatus) ? html.Replace("$funStatus$", "SwapDiv(3);") : html.Replace("$funStatus$", "");
            }
            else
            {
                html = html.Replace("$strStatus$", "<br><pre>    您还没有上传过文件！</pre>");
                html = html.Replace("$funStatus$", "");
            }
            output.Write(html);
        }

        /// <summary>
        /// 下拉列表选项转换器
        /// </summary>
        public class ClientObjectTypeControlsConverter : StringConverter
        {
            /// <summary>
            /// 构造函数
            /// </summary>
            public ClientObjectTypeControlsConverter() { }

            /// <summary>
            /// 下拉列表编辑属性
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
            {
                return true;
            }

            /// <summary>
            /// 获取标准值列表
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
            {
                ArrayList controlsArray = new ArrayList();
                controlsArray.Add("text");
                controlsArray.Add("object");
                controlsArray.Add("function");
                controlsArray.Add("func-obj");
                return new StandardValuesCollection(controlsArray);
            }

            /// <summary>
            /// return ture的话只能选,return flase可选可填 
            /// </summary>
            /// <param name="context"></param>
            /// <returns></returns>
            public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
            {
                return false;
            }
        }

        #region contact me
        public static string Help()
        {
            return @"mailto:354990393@qq.com";
        }
        #endregion
    }
}
